package io.github.wjehovah.yyn.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import io.github.wjehovah.yyn.R;
import io.github.wjehovah.yyn.adapter.SubscriptAdapter;
import io.github.wjehovah.yyn.bean.SubscriptBean;
import io.github.wjehovah.yyn.bean.SubscriptBean.SubscriptDetail;
import io.github.wjehovah.yyn.data.Budejie;

/**
 * 订阅界面
 * Created by yingchen on 2015/8/9.
 */
public class SubscriptActivity extends Activity implements AdapterView.OnItemClickListener{
    //返回
    private TextView mBackTextView;

    //标题
    private TextView mTitleTextView;

    //添加更多
    private ImageButton mMoreImageButton;

    //搜索
    private EditText mSearchEditText;

    //列表
    private ListView mListView;

    private FrameLayout mFrameLayout;

    //加载的ProgressBar
    private ProgressBar mLoadingProgressBar;


    private SubscriptBean subscriptBean;
    private List<SubscriptDetail> def_tags_data;
    private List<SubscriptDetail> rec_tags_data;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.subscript_activity);

        //初始化布局
        initViews();


        //访问网络请求数据
        getDataFromNet();

        //给ListView的item添加点击监听
        mListView.setOnItemClickListener(this);

        //监听搜索文本输入框
        mSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //Toast.makeText(SubscriptActivity.this,s,Toast.LENGTH_SHORT).show();
                if(count == 1){
                    Intent intent = new Intent(SubscriptActivity.this,SearchActivity.class);
                    startActivity(intent);
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    /**
     * 访问网络请求数据
     */
    private void getDataFromNet() {
       
       //使用异步任务访问服务器获取数据
        new AsyncTask<Void, Void, String>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(Void... params) {
                //在分线程访问服务器
                try {
                    URL url = new URL(Budejie.SUBSCRIPT_URL);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(3000);
                    connection.setReadTimeout(3000);
                    connection.setRequestMethod("GET");
                    connection.connect();

                    if(connection.getResponseCode() == 200){
                        InputStream is = connection.getInputStream();
                        String result =changeInputStreamToString(is);
                        if(!TextUtils.isEmpty(result)){
                            return result;
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                //隐藏进度条
                mLoadingProgressBar.setVisibility(View.GONE);

                //显示控件
                mBackTextView.setVisibility(View.VISIBLE);
                mTitleTextView.setVisibility(View.VISIBLE);
                mMoreImageButton.setVisibility(View.VISIBLE);
                mFrameLayout.setVisibility(View.VISIBLE);
                mListView.setVisibility(View.VISIBLE);


                //解析并处理数据
                if(!TextUtils.isEmpty(s)){
                    processData(s);
                }else{
                    Toast.makeText(SubscriptActivity.this,"访问网络失败",Toast.LENGTH_SHORT).show();

                }

            }
        }.execute();
    }


    /**
     * 解析并处理数据
     */
    public void processData(String json){
        //解析json数据
        subscriptBean = new Gson().fromJson(json, SubscriptBean.class);
        //Log.e("TAG","解析成功"+subscriptBean.toString());

        def_tags_data =subscriptBean.def_tags;
        rec_tags_data =subscriptBean.rec_tags;

        //显示ListView
        mListView.setAdapter(new SubscriptAdapter(def_tags_data, rec_tags_data, SubscriptActivity.this));

    }


    /**
     * 将输入流变成字符串
     * @param is
     * @return
     */
    private String changeInputStreamToString(InputStream is) throws Exception{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b =new byte[1024];
        int len;
        while((len = is.read(b))!=-1){
            baos.write(b,0,len);
        }
        return baos.toString();
    }


    /**
     * 初始化布局
     */
    public void initViews(){
      mBackTextView = (TextView) findViewById(R.id.tv_subscript_back);
      mMoreImageButton = (ImageButton) findViewById(R.id.ib_subscript_more);
      mSearchEditText = (EditText) findViewById(R.id.et_subscript_search);
      mListView = (ListView) findViewById(R.id.lv_subscript);
      mTitleTextView = (TextView) findViewById(R.id.tv_subscript_title);
      mFrameLayout = (FrameLayout) findViewById(R.id.fl_subscript_serach);
      mLoadingProgressBar = (ProgressBar) findViewById(R.id.pb_subscript_loading);
    }

    /**
     * 返回
     * @param view
     */
    public void back(View view){
        finish();
    }


    /**
     * 订阅列表的item的点击回调事件
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //
        if(position==0){
            //// TODO: 2015/8/10
        }else if(position == rec_tags_data.size()+1){
            return;
        }else if(position>0&&position<rec_tags_data.size()+1){
            String url = Budejie.SUBSCRIPT_ITEM_BASEURL+rec_tags_data.get(position-1).theme_id;
            String subScriptName = rec_tags_data.get(position-1).theme_name;
            enterDetailActivity(url,subScriptName);
        }else {
            String url = Budejie.SUBSCRIPT_ITEM_BASEURL+def_tags_data.get(position-rec_tags_data.size()-2).theme_id;
            String subScriptName = def_tags_data.get(position-rec_tags_data.size()-2).theme_name;
            enterDetailActivity(url,subScriptName);
        }
    }

    /**
     * 点击订阅列表的item进入新的Activity
     * @param url
     */
    public void enterDetailActivity(String url,String subScriptName){
        Intent intent = new Intent(SubscriptActivity.this,SubscriptDetailActivity.class);
        intent.putExtra("SUBSCRIPT_DETAIL",url);
        intent.putExtra("SUBSCRIPT_NAME",subScriptName);
        startActivity(intent);
    }
}
